package cn.sq.scaffold.ffmpeg.config;

import cn.sq.scaffold.ffmpeg.exception.BaseExeception;
import cn.sq.scaffold.ffmpeg.exception.FileChangeExeception;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2020/11/18
 * Time: 13:58
 * Description: 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class ExceptionController {

    //文件转化异常
    @ExceptionHandler(FileChangeExeception.class)
    public ResponseBean uploadexception(FileChangeExeception e) {
        return new ResponseBean(401, e.getMessage(), null);
    }

    //捕捉文件上传异常

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseBean uploadexception(MaxUploadSizeExceededException e) {

        return new ResponseBean(401, e.getMessage(), null);
    }

    /**
     * 错误值返回
     * @param e
     * @return
     */
    @ExceptionHandler(BaseExeception.class)
    public ResponseBean baseExeception(BaseExeception e) {
        return  e.getResponseBean();
    }
    @ExceptionHandler(MissingServletRequestPartException.class)
    public ResponseBean baseExeception(MissingServletRequestPartException e) {
        return  new ResponseBean(100, e.getRequestPartName(), e.getMessage());
    }


    //参数序列化异常（json）
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseBean handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return new ResponseBean(100, "Error: parameter (Is it json?)", e.getMessage());
    }
    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseBean handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return new ResponseBean(405, "Error: 405", e.getMessage());
    }

    /**
     * 404 - Not Found
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseBean noHandlerFoundException(NoHandlerFoundException e) {
        return new ResponseBean(404, "Error: 404", e.getMessage());

    }
}
